const express = require('express');
const app = express();
const fetch = require('node-fetch');
const ithome_url = 'https://www.ithome.com/rss/';
const parseString = require('xml2js').parseString;
const xml2js = require('xml2js');

app.get('/rss', function (req, res) {
    let filter = req.query.filter;
    var words = [];
    if (filter) {
        words = filter.split(",");
    }
    console.log(words);
    // 读取已存在的数据
    fetch(ithome_url)
        .then(res => res.text())
        .then(body => {
            parseString(body, function (err, result) {
                let items = result.rss.channel[0].item;
                // console.log(result.rss.channel[0].item);
                let filterResult = items.filter(item => {
                    let title = item.title[0];

                    let isDel = false;
                    words.forEach(word => {
                        if (title.indexOf(word) !== -1) {
                            console.log(title + '---filter true');
                            isDel = true;
                            return;
                        }
                    });
                    if (!isDel) {
                        return item;
                    }
                });
                //console.log(items.length + "," + filterResult.length);
                result.rss.channel[0].item = filterResult;
                //console.log(result.rss.channel[0].item.length);

                let builder = new xml2js.Builder();
                let xml = builder.buildObject(result);

                res.set('Content-Type', 'application/xml');
                res.send(xml);
            });


        });
});


const server = app.listen(8080, function () {

    let host = server.address().address;
    let port = server.address().port;

    console.log("应用实例，访问地址为 http://%s:%s", host, port)

});